/**
 * @file 工单操作-算账
 * @author yangjiangming <449654337@qq.com>
 * @date 2018-12-10 20:13:16
 */
layui.define(['layer', 'form', 'NP', 'laytpl', 'table', 'zmnUtils', 'Vue', '$http'], function (exports) {
    var $ = layui.$;
    var form = layui.form;
    var $http = layui.$http;
    var zmnUtils = layui.zmnUtils;
    var Vue = layui.Vue;
    var NP = layui.NP;
	var table = layui.table;
	var opCommonUtils = layui.list_modify_common;

    /**
     * 算账 url
     */
    var ACCOUNT_URL = '/work/modify/save/account.action';
    /**
     * 算账结果 url
     */
    var ACCOUNT_RESULT_URL = '/work/modify/account/result.action';

    let ERP_ACCOUNT_ENUM = {
        TRY: 2, // 预算张
    };

    let subsidy = Object.assign({}, accountVo.accountSubsidyVO, accountVo.accountMasterBonusVO);// 补贴奖励
	// 补贴奖励
	let subsidyBonus = [[
		{field: 'specialBenefit', title: '特殊补贴', templet: '#specialBenefit'},
		{field: 'springSubsidyRate', title: '春节期间补贴', templet: '#springSubsidyRate'},
        {field: 'standardPicBonus', title: '标准照片激励金', templet: e => zmnUtils.unit.fenToYuan(e.standardPicBonus)},
        {field: 'ontimeArriveBonus', title: '准时上门激励金', templet: e => zmnUtils.unit.fenToYuan(e.ontimeArriveBonus)},
        {field: 'timelyContactBonus', title: '及时联系激励金', templet: e => zmnUtils.unit.fenToYuan(e.timelyContactBonus)},
        {field: 'ontimeFinishBonus', title: '准时完工激励金', templet: e => zmnUtils.unit.fenToYuan(e.ontimeFinishBonus)},
        {field: 'userCommentBonus', title: '用户评价激励金', templet: e => zmnUtils.unit.fenToYuan(e.userCommentBonus)},
        {field: 'completeIn24Bonus', title: '24小时完成激励金', templet: e => zmnUtils.unit.fenToYuan(e.completeIn24Bonus)},
	]];

	let tips = function (ele, str, callback) {
		toast({
			title: str,
			icon: 2,
			time: 2000
		});
		$(ele).focus();
		$(ele).val('');
		if (typeof callback === 'function') {
			callback();
		}
		return false;
	};

    /**
	 * 提示消息
	 * @param str {string} 提示信息
	 * @returns {*}
	 */
	function toast(opt) {
		layer.msg(opt.title, {
			icon: opt.icon,
			time: opt.time || 1000,
		}, function () {
			if (opt.icon == 1) {
				opCommonUtils.goOperateHome();
				//    location.reload();
			}
		})
	};
    /**
     * 算账详情弹窗
     * @type {function(): {open: OpenAccountDetailModal}}
     * @type {function(): {open: performAccount}} 确认结果按钮执行方法
     */
    var AccountDetailModal = (function () {
        function creatAccountDetailComponent(orderSettleInfo, performAccount) {
            Vue.filter('fenToYuan', function (value) {
                return zmnUtils.unit.fenToYuan(value || 0);
            });
            Vue.filter('companyCommissionAmount', function (value) {
                return zmnUtils.unit.fenToYuan(NP.minus(value.manageCost || 0, NP.plus(value.artificialPreferences || 0, value.voucherShare || 0, value.integralCost || 0)));
            });
            Vue.filter('companyCommissionRate', function (value, settleInfo) {
                let base = NP.minus(settleInfo.internalStatementAmount || 0, orderSettleInfo.partsCost || 0, settleInfo.voucherCost || 0, settleInfo.integralCost || 0, settleInfo.discountCost || 0);
                if (!base || base == 0) {
                    return '0%';
                }
                return NP.times(NP.divide(NP.minus(value.manageCost || 0, NP.plus(value.artificialPreferences || 0, value.voucherShare || 0, value.integralCost || 0)), base), 100).toFixed(2) + '%';
            });

            var ApportionCard = {
                props: ['title', 'data'],
                template: '#template-account-detail-apportion'
            }

            var AccountDetail = {
                components: {
                    'apportion-card': ApportionCard
                },
                data: function () {
                    return {
                        orderSettleInfo
                    }
                },

                template: '#template-account-detail'
            }

            return AccountDetail;
        }

        function OpenAccountDetailModal (orderSettleInfo, performAccount) {
            var AccountDetail = creatAccountDetailComponent(orderSettleInfo);

            layer.open({
                type: 1,
                title: '算账明细',
                area: ['90%', '90vh'],
                content: '<div id="account-detail"></div>',
                success: function (layero, index) {
                    var container = layero.find('#account-detail')[0];

                    if (container) {
                        new Vue({
                            el: container,
                            components: {
                                'account-detail': AccountDetail,
                            },
                            methods: {
                                handleConfirmClick: function () {
                                    layer.close(index);
                                    if (zmnUtils.isFunction(performAccount)) {
                                        performAccount();
                                    }
                                }
                            },
                            template: `<account-detail @account="handleConfirmClick"></account-detail>`
                        });
                    }


                }
            });
        }

        return {
            open: OpenAccountDetailModal
        }
    })();
    /**
     * 获取算账结果
     * @param orderId 订单 id
     * @param workId 工单 id
     * @returns {*}
     */
    function fetchAccountResult (orderId, workId) {
        return $http.get(ACCOUNT_RESULT_URL, {
            orderId: orderId,
            workId: workId
        });
    }

    /**
     * 渲染算账结果
     * @param orderId 订单 id
     * @param workId 工单 id
     */
    function renderAccountResult (orderId, workId) {
        fetchAccountResult(orderId, workId).then(function (data) {
            new Vue({
                el: '#account-result',
                filters: {
                    fenToYuan: zmnUtils.unit.fenToYuan,
                    toMinus: function (value) {
                        return value ? NP.minus(0, value) : 0;
                    },
                    toPercent: function (value) {
                        return value + '%';
                    }
                },
                data: {
                    result: data
                },
                template: '#account-result-template'
            });
        });
    }

    /**
     * 验证textarea框内容长度 不能超过500字;
     */
    function verify() {
        form.verify({
            length : function (value) {
                if(value.length > 500){
                    return '最多输入500字!';
                }
            },
            validateReamrk : function (value, dom) {
                var flag = false;
                $("textarea.layui-textarea").each(function (ind, e) {
                    if ($(e).val()) {
                        flag = true;
                    }
                })
                if (!flag) {
                    return "备注必须填写一项";
                }
            }
        })
    }

    function saveAccount (data, btn) {
        return $http.lockSave(ACCOUNT_URL, data, btn);
    }

    /**
     * 预算账
     * @param data
     * @param btn
     */
    function tryErpAccount (data, btn) {
        var params = Object.assign({}, data, { tryErpAccount: ERP_ACCOUNT_ENUM.TRY });
        saveAccount(params).then(function (result) {
            AccountDetailModal.open(result, function () {
                realErpAccount(data, btn);
            });
        }, function (msg) {
            var reason = msg || '未知';
            zmnUtils.layui.toastError('预算账失败，原因：' + reason);
        });
    }


    /**
     * 算账
     * @param data
     * @param btn
     */
    function realErpAccount (data, buttonELm) {
        $http.lockSave(ACCOUNT_URL, data, buttonELm).then(function () {
        layer.msg('操作成功', { icon: 1, time: 3000 }, function () {
            opCommonUtils.goOperateHome();
        });
    }, (msg) => {
        layer.msg(msg);
    });
    }


    /**
     * 初始化页面
     */
    function initPage () {
        //补贴奖励
        table.render({
            elem: '#masteraccount-subsidy',
            cols: subsidyBonus,
            data: [subsidy],
        });
    }
    /**
     * 初始化页面事件
     */
    function initEvent () {
        //验证textarea长度 最多1000字
        verify();

		//特殊补贴
		$('.subsidy').on('keyup', '.specialBenefit', function (event) {
			let val = event.currentTarget.value;
			if(val==''){
				return;
			}
            var reg = /^-?\d*\.?\d{0,2}$/;
            if (!reg.test(val)) {
                tips(this, '只能输入数字及两位小数');
            }
            var specialBenefit = zmnUtils.unit.YuanToFen(+val)
            if ( specialBenefit > 100000000 || specialBenefit < -100000000) {
                tips(this, '只能输入1000000到-1000000中间的数字');
            }
		});
		$('.subsidy').on('blur', '.specialBenefit', function (event) {
			let val = event.currentTarget.value;
			if(val==''){
				return;
			}
            var reg = /^-?\d*\.?\d{0,2}$/;
            if (!reg.test(val)) {
                tips(this, '只能输入数字及两位小数')
            }
            var specialBenefit = zmnUtils.unit.YuanToFen(+val)
            if ( specialBenefit > 100000000 || specialBenefit < -100000000) {
                tips(this, '只能输入1000000到-1000000中间的数字');
            }
		});

        //保存按钮
        form.on('submit(savedata)',function (data) {
            var params = data.field;
            var buttonELm = data.elem;

            var isTryAccount = $(buttonELm).data('try') === 'yes';


            // ERP算账信息
            params = Object.assign({}, params, accountVo.accountMasterBonusVO);

            if (params.specialBenefit) {
                params.specialBenefit = zmnUtils.unit.YuanToFen(+params.specialBenefit);
            }

            // request(list, obj.elem);
            if (isTryAccount) {
                tryErpAccount(params, buttonELm);
            } else {
                realErpAccount(params, buttonELm);
            }

            return false
        })
    }

    // 程序入口
    function init () {


      // 初始化页面
      initPage();

      // 初始化事件
      initEvent();

    }


    // 初始化
    init();

    exports('oms_work_modify_remark');
});
